package org.nf.web;

import cn.hutool.core.util.ReflectUtil;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HandlesTypes;
import org.nf.web.config.Configure;

import java.util.Set;

/**
 * @author wangl
 * @date 2024/3/19
 * 容器启动时执行所有WebApplicationInitializer接口实现类的onStartup方法
 */
@HandlesTypes(WebApplicationInitializer.class)
public class FrameworkServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        //初始化配置信息
        initConfig(servletContext);
        //执行所有WebApplicationInitializer的实现类初始化方法
        if(set != null) {
            for(Class<?> clazz : set) {
                if(WebApplicationInitializer.class.isAssignableFrom(clazz)) {
                    WebApplicationInitializer initializer = (WebApplicationInitializer) ReflectUtil.newInstance(clazz);
                    initializer.onStartup(servletContext);
                }
            }
        }
    }

    /**
     * 如果ServletContext不存在Configure则初始化
     */
    private void initConfig(ServletContext servletContext) {
        if(servletContext.getAttribute(Configure.class.getName()) == null) {
            Configure config = Configure.init();
            servletContext.setAttribute(Configure.class.getName(), config);
        }
    }
}